package com.shoppingwebsite.filter;

import com.shoppingwebsite.domain.BaseContext;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *      检查用户是否已经完成登录
 */
@WebFilter(filterName = "loginUserFilter",urlPatterns = "/*")
public class LoginUserFilter extends OncePerRequestFilter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    /* *
     *    路径匹配，检查本次请求是否需要放行
     *       * urls是可放行的路径集合，requestURI是本地路径
     */
    public boolean check(String[] urls,String requestURI){
        for(String url:urls){
            boolean match = PATH_MATCHER.match(url, requestURI);           //PATH_MATCHER是对比路径是否相同（不能用字符串的对比，因为pages/page和pages/**是不同的）
            if (match) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //解决响应乱码问题
        response.setContentType("text/html;charset=utf-8");
        //1、获取本次请求的URI
        String requestUri = request.getRequestURI();

        //定义需要过滤的请求路径
        String urls[]=new String[]{
                "/pages/main.html",
                "/pages/shoppingList.html",
                "/order/getNow"
        };

        //2、判断本地请求是否需要处理
        boolean check = check(urls,requestUri);

        //3、不需要处理，直接放行
        if(check){
            filterChain.doFilter(request,response);
            return;
        }

        //已登录
        if(request.getSession().getAttribute("loginUser")!=null){
            //获取当前登录的id值
            Integer userId = (Integer) request.getSession().getAttribute("loginUser");
            //将id值存入本地线程
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        //没有登录，跳转到登陆页面
        PrintWriter writer = response.getWriter();
        writer.write("<h3>请<a href=\"/pages/login.html\">登录</a>，谢谢</h3>");
        return;
    }
}